# -*- coding: utf8 -*-


import json
import config
import datetime

from scrapy import Spider
from scrapy.http import Request
from sqlhelper import SqlHelper


class OkcoinDepth(Spider):
    name = 'depth'

    def __init__(self, name=None, **kwargs):
        super(OkcoinDepth, self).__init__(name, **kwargs)

        config = {
            'host': 'localhost',
            'port': 3306,
            'user': 'root',
            'password': '123456',
            'charset': 'utf8',
            'database': 'exchange'
        }

        self.sql = SqlHelper(db_name='exchange', db_config=config)

    def start_requests(self):
        currency_pair = ['btc_usd', 'ltc_usd', 'eth_usd', 'etc_usd', 'bch_usd']

        for currency in currency_pair:
            url = 'https://www.okcoin.com/api/v1/depth.do?symbol=%s' % currency

            yield Request(
                url = url,
                headers = {
                    # 'Host': 'block.cc',
                    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:55.0) Gecko/20100101 Firefox/55.0',
                },
                meta = {
                    'market_pair': currency
                },
                callback = self.currency_info
            )

    def currency_info(self, response):
        body = json.loads(response.body)

        # 交易对
        market_pair = response.meta.get('market_pair')

        # 卖方深度
        depth_asks = str(body.get('asks'))

        # 买方深度
        depth_bids = str(body.get('bids'))

        # 入库
        data = {
            'depth_pair': market_pair,
            'depth_asks': depth_asks,
            'depth_bids': depth_bids,
        }
        self.sql.insert_json(data, table_name='exchange_depth', commit=True)

    # close
    def close(spider, reason):
        spider.sql.commit()


# 数据库
'''
CREATE TABLE `exchange_depth` (
  `depth_id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '市场深度，索引ID',
  `depth_asks` text COMMENT '卖方深度',
  `depth_bids` text COMMENT '买方深度',
  PRIMARY KEY (`depth_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
'''